//
//  TripListViewModel.swift
//  ImGuider X
//
//  Created by 陆涛 on 2018/9/28.
//  Copyright © 2018 imguider. All rights reserved.
//

import UIKit

class TripListViewModel: NSObject {
    
    override init() {
        super.init()
        
        NotificationCenter.default.addObserver(self, selector: #selector(reloadFinished(notif:)), name: NSNotification.Name("reloadTripFinished"), object: nil)
    }
    
    deinit {
        
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc private func reloadFinished(notif:Notification) {
        
        let errmsg = notif.userInfo?["errmsg"] as? String
        self.loadFinished?(errmsg)
    }

    var dataSource:[Trip]? {
        
        return TripManager.share.trips
    }
    
    var loadFinished:((String?)-> Void)?
    
    
    func reloadData() {
        
        TripManager.share.reloadTripData()
    }
    
    func bindTrip(tripid:String) {
        
        TripManager.share.bindTrip(tripid: tripid) {
            
            [weak self] errmsg in
            guard let `self` = self else { return }
            
            
            if let errmsg = errmsg {
                
                self.loadFinished?(errmsg)
                return
            }
            
            self.reloadData()
        }
    }
}
